/*************************************
Copyright 2011 Chinua Iloabachie, Pradnya Khutafale, Siyi Liu, Junichi Suzuki, and The University of Massachusetts, Boston (http://code.google.com/p/tabletuml/)


Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 
*************************************/



package touchMe.Draw;

import touchMe.Help.WebHelp;
import touchMe.Util.DiagramManager;
import touchMe.Util.Mail;
import touchMe.baseClass.Constants;
import touchMe.baseClass.Diagram;
import touchMe.baseClass.ElementType;
import touchMe.Util.DiagramFileHandler;
import touchMe.baseClass.Element;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public class TouchMe extends Activity implements OnTouchListener{
	
	 public static String filePath="";
	 private PointF start= new PointF();
	 private PointF endp= new PointF();
	 private int mode= Constants.NONE;
	 boolean savedDiagram=true;
	  
	DrawClass mCustomDrawableView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // If user starts drawing diagram w/o doinf File->New
        //then consider it as new File option
        if(Constants.explorerMode<=0)
        {	
        	Constants.explorerMode=Constants.NEW;
        	Diagram.getInstance().setNewDiagram(true);
        	Diagram.getInstance().setFilename("");
        } 	
        String fpath=getIntent().getStringExtra(filePath);
        if(fpath==null)
      	  fpath="";
        Log.d(Constants.TAG,"filePath:"+fpath);
        if(fpath.length()>0){
     	    DiagramManager.read(this, fpath);
     	    Diagram.getInstance().setNewDiagram(false);
     	    //mCustomDrawableView.invalidate();// we need to clear screen
        }
       mCustomDrawableView = new DrawClass(this);
	   mCustomDrawableView.setOnTouchListener(this);
	   setContentView(mCustomDrawableView);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();    
    	inflater.inflate(R.menu.menu, menu);
    	Log.d(Constants.TAG,"Menu menu");
		return super.onCreateOptionsMenu(menu);
	}
    /**
     * This method is called when user clicks an option from Menu
     * This method performs the action like opening file, saving file etc. 
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	Log.d(Constants.TAG,"onOptionsItemSelected "+item.getItemId());
    	switch(item.getItemId()){
    	case R.id.Open_File:
    		if(Diagram.getInstance().getFilename()!=null)
        		DiagramManager.clearInstance();
    		Log.d(Constants.TAG,"Clicked Open File");
    		Constants.explorerMode=Constants.OPEN;
    		mCustomDrawableView.invalidate();
    		DiagramManager.clearInstance();
    		Intent intent=new Intent(TouchMe.this, AndroidExplorer.class);
        	startActivity(intent);
    		return true;
    		
    	case R.id.Email_File:
    		if(Diagram.getInstance().getFilename()!=null){
        		Mail.sendDiagram(this, "",Diagram.getInstance().getFilename());
    		}else
    			Toast.makeText(this, "Save the diagram first", 1000).show();
    		return true;
    	case R.id.Edit_File:
    		Constants.explorerMode=Constants.EDITMODE;
    		Constants.diagramState=Constants.EDITMODE;
    		if(DiagramManager.getUmlDiagram().getElements().size()>0){
    			Toast.makeText(this, "Edit mode", 1000).show();
    			 
    		}else
    			Toast.makeText(this, "No diagram", 2000).show();
    		return true;
    	case R.id.Save_File:
    		Constants.explorerMode=Constants.SAVE;
    		Log.d(Constants.TAG,"Clicked Save File");
    		savedDiagram=true;
    		Diagram diagramObj=Diagram.getInstance();
    		if(diagramObj.isNewDiagram())
    		{
	    		Intent saveIntent=new Intent(TouchMe.this, AndroidExplorer.class);
	        	startActivity(saveIntent);
        	}
    		else
    		{
    			DiagramFileHandler.writeDiagram(Diagram.getInstance().getFilename(), 
    			Diagram.getInstance());    			
    		}	
    		
    		return true;
    	case R.id.SaveAs_File :
    		savedDiagram=true;
    		Constants.explorerMode=Constants.SAVEAS;
    		Log.d(Constants.TAG,"Clicked SaveAs ");	
    		Intent saveAsIntent=new Intent(TouchMe.this, AndroidExplorer.class);
        	startActivity(saveAsIntent);
    		
    	    return true;
    	case R.id.New_File:
    		Constants.explorerMode=Constants.NEW;
    		Log.d(Constants.TAG,"Clicked New File");
    		Constants.explorerMode=Constants.NEW;
    		if(savedDiagram==false){
    			//ask the use if s/he wants to save
        		//if save open save dialog, then redraw screen
    			AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
                alertbox.setMessage("Will you like to save the current diagram?");
                alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    	if(Diagram.getInstance().isNewDiagram())
                		{
            	    		Intent saveIntent=new Intent(TouchMe.this, AndroidExplorer.class);
            	        	startActivity(saveIntent);
                    	}
                		else
                		{
                			DiagramFileHandler.writeDiagram(Diagram.getInstance().getFilename(), 
                			Diagram.getInstance());
                    		newFile();
                		}	
                    }
                });
                alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    	newFile();
                    }
                });
                alertbox.show();
    		}
    		else{
    			Toast.makeText(this, "New diagram", 2000).show();
    			newFile();
    		}
    		return true;
    	case R.id.ClassDiagram:
    		Log.d(Constants.TAG,"Clicked on classDiagram");
    		Dialog v=new PropertyBox(this,Constants.panelAtt,0,null,Constants.classType);
    		v.show();
    		return true;
    		
    	case R.id.Association:
    		Log.d(Constants.TAG,"Clicked on Association");
    		Constants.explorerMode=Constants.RELATIONMODE;
    		// line below commented by Pradnya
    		//DiagramManager.modifyDiagram(Constants.relationType, "lt=<<-<", Constants.ADDELEMENT);
    		return true;
    	case R.id.Inherit:
    		Constants.explorerMode=Constants.INHERITANCE_RELATIONMODE;
    		Log.d(Constants.TAG,"Clicked on Inheritance");
    		    		
    		return true;
    	case R.id.Implement:
    		Log.d(Constants.TAG,"Clicked on Implementation");
    		Constants.explorerMode=Constants.IMPLEMENTATION_RELATIONMODE;
    		return true;
    		
    	case R.id.UseCase:
    		Log.d(Constants.TAG,"Clicked on Use diagram");
    		Dialog dialogView=new PropertyBox(this,Constants.useCasePanelAtt,0,null,Constants.usecaseType);
    		dialogView.show();
    		return true;
    	case R.id.Actor:
    		Log.d(Constants.TAG,"Clicked on Actor");
    		Dialog dialog=new PropertyBox(this,Constants.actorAtt,0,null,Constants.actorType);
    		dialog.show();
    		return true;
    	case R.id.Help:
    		//Intent helpIntent=new Intent(TouchMe.this, WebHelp.class);
        	//startActivity(helpIntent);
    		showHelp("");
        	return true;
    	case R.id.Exit_App:
    		Constants.explorerMode=Constants.EXIT;
    		mCustomDrawableView.invalidate();
    		DiagramManager.clearInstance();
    		this.moveTaskToBack(true);
    		finish();
    		/*
    		
    		
    		android.os.Process.killProcess(android.os.Process.myPid());
    		*/
    		
    		
    		return true;
    	}
    	return false;
    }
    public void newFile(){
    	savedDiagram=true;
    	DiagramManager.clearInstance();
    	Diagram.getInstance().setNewDiagram(true);
    	mCustomDrawableView.invalidate();
		mCustomDrawableView = new DrawClass(this);
 	    setContentView(mCustomDrawableView);
 	   	mCustomDrawableView.setOnTouchListener(this);
    }
    public void updateDeleteModell(String elementID, String propertyString,int mode1){
    		boolean resp=DiagramManager.modifyDiagram(elementID, propertyString, mode1);
    		if(resp==true){
    			savedDiagram=false;
    			Log.d(Constants.TAG,"Refresh diagram");
    			mCustomDrawableView.invalidate();
    			mCustomDrawableView = new DrawClass(this);
    	 	    setContentView(mCustomDrawableView);
    	 	   	mCustomDrawableView.setOnTouchListener(this);
    		}			
    } 
    public void createNewModell(String type, String propertyString,int mode1){
		String mType=type;
		savedDiagram=false;
		DiagramManager.modifyDiagram(mType, propertyString, mode1);
		Log.d(Constants.TAG,"New class/use case diagram/relation");
		mCustomDrawableView.invalidate();
		mCustomDrawableView = new DrawClass(this);
 	    setContentView(mCustomDrawableView);
 	   	mCustomDrawableView.setOnTouchListener(this);
    } 
    
	@Override
	public boolean onTouch(View mView, MotionEvent event) {
		//dumpEvent(event); //uncomment only when debugging
		switch (event.getAction() & MotionEvent.ACTION_MASK)
		{
		case MotionEvent.ACTION_DOWN:
		  start.x= event.getX(); 
		  start.y= event.getY();
		if(Constants.explorerMode==Constants.RELATIONMODE)
		   {		
			//DiagramManager.checkPosition(start.x, start.y);
			mode=Constants.RELATIONMODE;}
		else if(Constants.explorerMode==Constants.INHERITANCE_RELATIONMODE)
		   {		
			 mode=Constants.INHERITANCE_RELATIONMODE;}
		else if(Constants.explorerMode==Constants.IMPLEMENTATION_RELATIONMODE)
		   { mode=Constants.IMPLEMENTATION_RELATIONMODE;}
		
		else
		     mode = Constants.DRAG;
		
		//Log.d(Constants.TAG, "mode=DRAG" );
		
		break;
		case MotionEvent.ACTION_UP:
          {
        	  
        	 if((Constants.diagramState==0) && ((mode==Constants.IMPLEMENTATION_RELATIONMODE)||
  					(mode==Constants.INHERITANCE_RELATIONMODE)|| 
  					mode==Constants.RELATIONMODE) )
  			{
  				endp.x=event.getX();
  				endp.y=event.getY();
  				mCustomDrawableView.invalidate();
  				if(mode==Constants.RELATIONMODE)
  				 mCustomDrawableView = new DrawClass(this,start.x,start.y,endp.x,endp.y,Constants.RELATIONMODE);
  				else if (mode==Constants.INHERITANCE_RELATIONMODE)
   				   mCustomDrawableView = new DrawClass(this,start.x,start.y,endp.x,endp.y,Constants.INHERITANCE_RELATIONMODE);
   				else if(mode==Constants.IMPLEMENTATION_RELATIONMODE)
   					 mCustomDrawableView = new DrawClass(this,start.x,start.y,endp.x,endp.y,Constants.IMPLEMENTATION_RELATIONMODE);
   					
  		 	    setContentView(mCustomDrawableView);
  		 	   	mCustomDrawableView.setOnTouchListener(this);	
  		 	   	mode=Constants.RELATION_DRAWN;
  		 	    Constants.explorerMode=0;
  			}
        	 //lines below commented by PRadnya
        	/*if ((mode==Constants.association)&&(Constants.diagramState==0)){
			if(DiagramManager.checkPositiontoadd(start.x, start.y,endp.x,endp.y))
			{ 
				mCustomDrawableView.invalidate();
			    mCustomDrawableView = new DrawClass(this);
	 	        setContentView(mCustomDrawableView);
	 	   	    mCustomDrawableView.setOnTouchListener(this);
	 	        //Log.d(Constants.TAG, "mode=MOVE DRAWN -----------" );
	 	       Constants.explorerMode=0;
				//Constants.diagramState=0;
			}//end if					
		   }  //endif*/
        	 
          }
		case MotionEvent.ACTION_POINTER_UP:
			if(Constants.diagramState==Constants.EDITMODE){
				mode = Constants.NONE;
				//line below commented by Pradnya
				//Element elem=DiagramManager.search4PanelAtt(start.x,start.y);
				Element elem=DiagramManager.moveOrSearch(start.x, start.y, 0, 0, true);
				if(elem!=null){
				   if(elem.getType()== ElementType.INHERITANCE || 
						   elem.getType()== ElementType.IMPLEMENTATION)
				   { 
					Dialog v1=new PropertyBox(this,"",1,elem.toString(),"INHERI_IMPLEMENT");
					v1.show();
				   }
				   else if
				   (elem.getType()== ElementType.SIMPLE_ASSOC)
				   { 
					Dialog v1=new PropertyBox(this,elem.getPanelAttributes().toString(),1,elem.toString(),Constants.relationType);
					v1.show();
				   }
				   else
				   { // for all others edit
					   Dialog v2=new PropertyBox(this,elem.getPanelAttributes().toString(),1,elem.toString(),Constants.classType);
		    		    v2.show();
				   }	    
				}
				Constants.explorerMode=0;
				Constants.diagramState=0;
			}
		break;
		
		case MotionEvent.ACTION_MOVE:
			if((mode==Constants.DRAG)&&(Constants.diagramState==0))
			{
				savedDiagram=false;
				//Log.d(Constants.TAG, "mode=MOVE------"+event.getY() );
			 	float draggedToX=event.getX()-start.x;
				float draggedToY=event.getY()-start.y;
				DiagramManager.moveOrSearch(start.x,start.y,draggedToX,draggedToY,false);
				mCustomDrawableView.invalidate();
				mCustomDrawableView = new DrawClass(this);
		 	    setContentView(mCustomDrawableView);
		 	   	mCustomDrawableView.setOnTouchListener(this);
		 	    //Log.d(Constants.TAG, "mode=MOVE DRAWN -----------" );
		 	    start.x=event.getX();
		 	    start.y=event.getY();
			}	
			else if ((mode==Constants.association)&&(Constants.diagramState==0))
			{
				//Log.d(Constants.TAG, "mode=association------"+event.getY() );
				savedDiagram=false;
				endp.x=event.getX();
				endp.y=event.getY();
				mCustomDrawableView.invalidate();
				mCustomDrawableView = new DrawClass(this,start.x,start.y,endp.x,endp.y,Constants.RELATIONMODE);
		 	    setContentView(mCustomDrawableView);
		 	   	mCustomDrawableView.setOnTouchListener(this);
		 	    mode=Constants.RELATION_DRAWN;
 		 	    Constants.explorerMode=0;
				
			}
			

		break;
		}
		
		return true;
	}
	
	private void dumpEvent(MotionEvent event){
		 
		Log.d(Constants.TAG, "INSIDE DUMP" );
    	String names[]={"DOWN","UP","MOVE","CANCEL","OUTSIDE",
    			"POINTER_DOWN","POINTER_UP","7?","8?","9?"};
    	StringBuilder sb=new StringBuilder();
    	int action =event.getAction();
    	int actionCode=action & MotionEvent.ACTION_MASK;
    	sb.append("event ACTION_").append(names[actionCode]);
    	if(actionCode==MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP){
    		sb.append("(pid").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
    		sb.append(")");
    	}
    	sb.append("[");
    	for(int i=0;i<event.getPointerCount();i++){
    		sb.append("#").append(i);
    		sb.append("(pid ").append(event.getPointerId(i));
    		sb.append(")=").append((int) event.getX(i));
    		sb.append(",").append((int) event.getY(i));
    		if(i+1<event.getPointerCount())
    			sb.append(";");
    	}
    	sb.append("]");
    	Log.d(Constants.TAG,sb.toString());
    }
	public void showHelp(String topic){
		Intent helpIntent=new Intent(TouchMe.this, WebHelp.class);
		helpIntent.putExtra("topic", topic);
    	startActivity(helpIntent);
	}
	
}